package com.sto.stoapp.db.manager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.db.constant.StoOrderConstant;
import com.sto.stoapp.http.response.download.info.OrderRecordInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

public class OrderManager extends StoDataBase implements
		DownLoadDao<OrderRecordInfo> {
	private static OrderManager manager;

	// private static final String SQL_QUERY_ALL = "select * from " +
	// ORDER_DOWNLOAD_TABLE
	// + " where 1=1";

	private static final String SQL_QUERY_COUNT = "select count(*) from "
			+ ORDER_DOWNLOAD_TABLE + " where 1=1";

	private static final String SQL_QUERY_ORDER = "select count(*) from "
			+ ORDER_DOWNLOAD_TABLE;

	private static final String SQL_QUERY_ORDER_NOTICE = "select * from "
			+ ORDER_DOWNLOAD_TABLE;

	private Context context;

	private OrderManager(Context context) {
		super(context);
		this.context = context;
	}

	/**
	 * 单例化对象
	 * 
	 * @param context
	 * @return
	 */
	public static OrderManager getInstance(Context context) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			if (manager == null) {
				manager = new OrderManager(context);
			}
			return manager;
		}
	}

	// /**
	// * 插入单条数据
	// *
	// * @param entity
	// * @return
	// */
	// public boolean insert(OrderEntity entity) {
	// synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
	// long res = -1;
	// OrderEntity orderEntity = null;
	// if (entity instanceof OrderEntity) {
	// orderEntity = (OrderEntity) entity;
	// } else {
	// return false;
	// }
	// try {
	// ContentValues values = new ContentValues();
	// values.put(PICKUP_MEMBERS, orderEntity.getPickupMembers());
	// values.put(PICKUP_NETWORK, orderEntity.getPickupNetwork());
	// values.put(ORDER_NUMBER, orderEntity.getOrderNumber());
	// values.put(ORDER_DATE, orderEntity.getOrderDate());
	// values.put(CLIENT_NUMBER, orderEntity.getClientNumber());
	// values.put(SEND_CLIENT, orderEntity.getSendClient());
	// values.put(SEND_CLIENT_ADDRESS,
	// orderEntity.getSendClientAddress());
	// values.put(SEND_CONTACT_PRESON,
	// orderEntity.getSendContactPreson());
	// values.put(SEND_CONTACT_TELEPHONE,
	// orderEntity.getSendContactTelehone());
	// values.put(SEND_CONTACT_PHONE,
	// orderEntity.getSendContactPhone());
	// values.put(DESTINATION, orderEntity.getDestination());
	// res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
	// .insert(ORDER_DOWNLOAD_TABLE, null, values);
	// if (res > 0) {
	// Log.d("插入一条订单表", "成功");
	// } else {
	// Log.d("插入一条订单表", "失败");
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// ExceptionLog.writeLog("insert", e.getMessage());
	// } finally {
	// closeDb(UnifiedStaticType.WRITE_DATABASE);
	// }
	// return res > 0 ? true : false;
	// }
	// }

	/**
	 * 删除某一条订单
	 * 
	 * @param orderCode
	 * @return
	 */
	public boolean deleteOnly(String orderCode) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				// System.out.println("**orderCode***" + orderCode);
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(ORDER_DOWNLOAD_TABLE, ODER_NO + "= ?",
								new String[] { orderCode });
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteOnly", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}

	/**
	 * 更新订单状态
	 * 
	 * @param orderCode
	 * @return
	 */
	public boolean updateOrder(String orderCode, String status) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				String sql = "update " + ORDER_DOWNLOAD_TABLE + " set "
						+ ORDER_STATUS + " = ? " + " where " + ODER_NO + " = ?";

				db.execSQL(sql, new Object[] { status, orderCode });
				// (ORDER_DOWNLOAD_TABLE,
				// ORDER_NUMBER + "= ?", new String[] { orderCode});
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteOnly", e.getMessage());
			} finally {
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}

	/**
	 * 更新订单状态
	 * 
	 * @param orderCode
	 * @param status
	 * @param noticeType
	 *            提示状态 (0)/取消 (1)/催促 default(取消)
	 * @return
	 */
	public boolean updateOrder(String orderCode, String status,
			String noticeType) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				String sql = "update " + ORDER_DOWNLOAD_TABLE + " set "
						+ URGE_TAG + " = ? " + " where " + ODER_NO + " = ?";

				db.execSQL(sql, new Object[] { noticeType, orderCode });
				// (ORDER_DOWNLOAD_TABLE,
				// ORDER_NUMBER + "= ?", new String[] { orderCode});
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteOnly", e.getMessage());
			} finally {
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}

	/**
	 * 删除七天之外的订单
	 * 
	 * @param orderCode
	 * @return
	 */
	public boolean deleteWeek() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				// System.out.println("**orderCode***" + orderCode);
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(ORDER_DOWNLOAD_TABLE,
								ODER_TIME
										+ "< date('now', 'localtime','-7 day')",
								null);
				// getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
				// .delete(ORDER_RESPONSE_TABLE,
				// ORDER_DOWN_DATE + "< date('now', 'localtime','-7 day')",
				// null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteOnly", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}

	/**
	 * 批量更新数据
	 * 
	 * @param datas
	 */
	// public void insertList(List<OrderEntity> datas) {
	// synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
	// int length = datas.size();
	// SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
	// try {
	// db.beginTransaction();
	// for (int i = 0; i < length; i++) {
	// long res = -1;
	// OrderEntity orderEntity = null;
	// if (datas.get(i) instanceof OrderEntity) {
	// orderEntity = (OrderEntity) datas.get(i);
	// } else {
	// continue;
	// }
	// ContentValues values = new ContentValues();
	// values.put(PICKUP_MEMBERS, orderEntity.getPickupMembers());
	// values.put(PICKUP_NETWORK, orderEntity.getPickupNetwork());
	// values.put(ORDER_NUMBER, orderEntity.getOrderNumber());
	// values.put(ORDER_DATE, orderEntity.getOrderDate());
	// values.put(CLIENT_NUMBER, orderEntity.getClientNumber());
	// values.put(SEND_CLIENT, orderEntity.getSendClient());
	// values.put(SEND_CLIENT_ADDRESS,
	// orderEntity.getSendClientAddress());
	// values.put(SEND_CONTACT_PRESON,
	// orderEntity.getSendContactPreson());
	// values.put(SEND_CONTACT_TELEPHONE,
	// orderEntity.getSendContactTelehone());
	// values.put(SEND_CONTACT_PHONE,
	// orderEntity.getSendContactPhone());
	// values.put(DESTINATION, orderEntity.getDestination());
	// values.put(BACKUPS_THREE, orderEntity.getRemark());
	// values.put(ORDER_DOWN_DATE,
	// dateFormat(orderEntity.getOrderNumber())); // new
	// // SimpleDateFormat("yyyy-MM-dd").format(new
	// // Date())
	// values.put(BACKUPS_ONE, "");
	//
	// res = db.insert(ORDER_DOWNLOAD_TABLE, null, values);
	// db.execSQL(
	// "insert into "
	// + ORDER_RESPONSE_TABLE
	// + "("
	// + PICKUP_MEMBERS
	// + ", "
	// + PICKUP_NETWORK
	// + ", "
	// + ORDER_NUMBER
	// + ", "
	// + CLIENT_NUMBER
	// + ", "
	// + ORDER_STATUS
	// + ", "
	// + ORDER_DOWN_DATE
	// + ") values(?,?,?,?,?, date('now','localtime'))",
	// new Object[] {
	// StoFilePreference.getInstance(context)
	// .getUserInfo(),
	// orderEntity.getPickupNetwork(),
	// orderEntity.getOrderNumber(),
	// StoFilePreference.getInstance(context)
	// .getMachineCode(), "0" });
	// if (res > 0) {
	// Log.d("插入一条订单表", "成功");
	// } else {
	// Log.d("插入一条订单表", "失败");
	// }
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// ExceptionLog.writeLog("insertList", e.getMessage());
	// } finally {
	// datas.clear();
	// db.setTransactionSuccessful();
	// db.endTransaction();
	// closeDb(UnifiedStaticType.WRITE_DATABASE);
	// }
	// }
	// }

	private String dateFormat(String parameters) {
		String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		if (parameters.length() > 8) {
			date = parameters.substring(0, 4) + "-"
					+ parameters.substring(4, 6) + "-"
					+ parameters.substring(6, 8);
		}
		return date;
	}

	/**
	 * 查询订单的数量
	 * 
	 * @return
	 */
	public int queryAllCount() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int count = 0;
			Cursor cursor = null;
			try {
				cursor = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
						.rawQuery(SQL_QUERY_COUNT, null);
				if (cursor != null && cursor.moveToFirst()) {
					count = cursor.getInt(0);
				}
				closeCursor(cursor);
			} finally {
				closeCursor(cursor);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return count;
		}
	}

	/**
	 * 查询订单的是否已处理
	 * 
	 * @return 不存在改订单
	 */
	public boolean queryOrderIsProcess(String orderCode) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int count = 0;
			boolean ret = false;
			Cursor cursor = null;
			try {
				cursor = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
						.rawQuery(SQL_QUERY_ORDER + " where " + ODER_NO + "=?",
								new String[] { orderCode });
				if (cursor != null && cursor.moveToFirst()) {
					count = cursor.getInt(0);
				}
				closeCursor(cursor);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(cursor);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			if (count == 0) {
				ret = true;
			}
			return ret;
		}
	}

	/**
	 * 查询订单的是否已提取(1)
	 * 
	 * @return
	 */
	public boolean queryOrderIsExtract(String orderCode) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int count = 0;
			boolean ret = false;
			Cursor cursor = null;
			try {
				cursor = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
						.rawQuery(
								SQL_QUERY_ORDER + " where " + ODER_NO
										+ "=? and status=?",
								new String[] { orderCode, "1" });
				if (cursor != null && cursor.moveToFirst()) {
					count = cursor.getInt(0);
				}
				closeCursor(cursor);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(cursor);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			if (count > 0) {
				ret = true;
			}
			return ret;
		}
	}

	// public OrderNoticeEntity getSingleOrderNoticeInfo(String orderCode) {
	// OrderNoticeEntity entity = new OrderNoticeEntity();
	// synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
	// Cursor cursor = null;
	// try {
	// cursor = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
	// .rawQuery(
	// SQL_QUERY_ORDER_NOTICE + " where orderNumber=?",
	// new String[] { orderCode });
	// if (cursor != null && cursor.moveToFirst()) {
	// entity.setClientName(cursor.getString(cursor
	// .getColumnIndex(SEND_CONTACT_PRESON)));
	// entity.setClinetPhone(cursor.getString(cursor
	// .getColumnIndex(SEND_CONTACT_PHONE)));
	// entity.setClinetAddress(cursor.getString(cursor
	// .getColumnIndex(SEND_CLIENT_ADDRESS)));
	// }
	// closeCursor(cursor);
	// } catch (Exception e) {
	// e.printStackTrace();
	// } finally {
	// closeCursor(cursor);
	// closeDb(UnifiedStaticType.READ_DATABASE);
	// }
	// }
	// return entity;
	// }

	@Override
	public void insertOrReplace(List<OrderRecordInfo> entitys) {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (OrderRecordInfo info : entitys) {
					ContentValues values = buildContentValues(info);
					if (replace(values)) {
						Log.d("插入一条订单下载", "成功");
					} else {
						Log.d("插入一条订单下载", "失败");
					}
					// }
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}

	}

	@Override
	public boolean replace(ContentValues values) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long result = 0;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				result = db.replace(ORDER_DOWNLOAD_TABLE, null, values);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result > 0;
		}
	}

	@Override
	public void deleteDataByStatus(String status) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {

			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				db.delete(ORDER_DOWNLOAD_TABLE, StoOrderConstant.ORDER_STATUS
						+ "=?", new String[] { status });
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}
	}

	@Override
	public String getMaxVersion() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ContentValues buildContentValues(OrderRecordInfo entity) {
		ContentValues values = new ContentValues();
		values.put(StoOrderConstant.CONTACT_ADDRESS, entity.contactAddress);
		values.put(StoOrderConstant.CONTACT_MOBILE_PHONE,
				entity.contactMobilePhone);
		values.put(StoOrderConstant.CONTACT_NAME, entity.contactName);
		values.put(StoOrderConstant.CONTACT_PHONE, entity.contactPhone);

		values.put(StoOrderConstant.CUSTOMER_NAME, entity.customerName);
		values.put(StoOrderConstant.CUSTOMER_NO, entity.customerNo);
		values.put(StoOrderConstant.CUSTOMER_REMARK, entity.customerRemark);
		values.put(StoOrderConstant.DES_AREA_CODE, entity.desAreaCode);
		values.put(StoOrderConstant.EMP_CODE, entity.empCode);
		values.put(StoOrderConstant.ODER_NO, entity.oderNo);
		values.put(StoOrderConstant.ODER_TIME, entity.oderTime);
		values.put(StoOrderConstant.ORDER_STATUS, entity.oderStatus);
		values.put(StoOrderConstant.URGE_TAG, entity.urgeTag);

		return values;
	}

	public List<OrderRecordInfo> queryAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			List<OrderRecordInfo> data = null;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
				data = getDataFromCursor(getSqliteDatabase(
						UnifiedStaticType.READ_DATABASE).rawQuery(
						SQL_QUERY_ORDER_NOTICE, null));
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return data;
		}

	}

	private List<OrderRecordInfo> getDataFromCursor(Cursor cursor) {
		List<OrderRecordInfo> infos = new ArrayList<OrderRecordInfo>();
		if (cursor != null) {
			while (cursor.moveToNext()) {
				OrderRecordInfo info = new OrderRecordInfo();
				info.contactAddress = cursor.getString(cursor
						.getColumnIndex(CONTACT_ADDRESS));
				info.contactMobilePhone = cursor.getString(cursor
						.getColumnIndex(CONTACT_MOBILE_PHONE));
				info.contactName = cursor.getString(cursor
						.getColumnIndex(CONTACT_NAME));
				info.contactPhone = cursor.getString(cursor
						.getColumnIndex(CONTACT_PHONE));
				info.customerName = cursor.getString(cursor
						.getColumnIndex(CUSTOMER_NAME));
				info.customerNo = cursor.getString(cursor
						.getColumnIndex(CUSTOMER_NO));
				info.customerRemark = cursor.getString(cursor
						.getColumnIndex(CUSTOMER_REMARK));
				info.desAreaCode = cursor.getString(cursor
						.getColumnIndex(DES_AREA_CODE));
				info.empCode = cursor
						.getString(cursor.getColumnIndex(EMP_CODE));
				info.oderNo = cursor.getString(cursor.getColumnIndex(ODER_NO));
				info.oderStatus = cursor.getString(cursor
						.getColumnIndex(ORDER_STATUS));
				info.oderTime = cursor.getString(cursor
						.getColumnIndex(ODER_TIME));
				info.urgeTag = cursor
						.getString(cursor.getColumnIndex(URGE_TAG));
				infos.add(info);
			}
		}

		closeCursor(cursor);
		return infos;
	}

	@Override
	public void deleteAll() {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(ORDER_DOWNLOAD_TABLE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}

	}
}
